import 'dart:io';
import 'dart:math';

import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:x3_base_core/base_configs/service_config.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:x3_base_core/base_enums/base_image_type_enum.dart';
import 'package:x3_base_core/base_utils/base_storage_util.dart';
import 'package:x3_base_core/base_enums/base_image_size_enum.dart';

class BaseUtils {
  BaseUtils._();

  /// 弹出SnackBar toastLength:LENGTH_SHORT/LENGTH_LONG
  static showToast(String message, {String toastLength = "LENGTH_SHORT"}) {
    if (message == null || message.isEmpty || message.length == 0) return;
    Fluttertoast.cancel();
    Toast _toastLength = toastLength == "LENGTH_LONG" ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
    Fluttertoast.showToast(msg: message, gravity: ToastGravity.CENTER, toastLength: _toastLength, textColor: Colors.white, backgroundColor: Colors.black);
  }

  /// 判断是否为非空
  static bool isNotEmpty(dynamic value) {
    return value != null && value.toString().isNotEmpty;
  }

  /// 为避免Text会将长字母、数字串整体显示省略,将每个字符串之间插入零宽空格
  static String insertZeroWidthSpaces(String text) {
    if (text == null || text.isEmpty) return text;
    String breakText = '';
    text.runes.forEach((element) {
      breakText += String.fromCharCode(element);
      breakText += '\u200B';
    });
    return breakText;
  }

  /// 判断当前是否为数字
  static bool isNumber(String data) {
    if (data.length > 0) {
      RegExp regex = new RegExp(r"^[0-9]*[1-9][0-9]*$");
      return regex.hasMatch(data);
    }
    return false;
  }

  ///判断当前手机是否输入正确
  ///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
  /// 此方法中前三位格式有：
  /// 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
  static bool isMobileEnteredCorrectly({@required String mobile}) {
    if (mobile == null || mobile.isEmpty) return false;
    return RegExp(r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$').hasMatch(mobile);
  }

  /// 手机号正则
  static String getRegularPhoneNumber = "^1[0-9]{10}\$";

  /// 获取当前map中的数据
  static dynamic getKeyData(dynamic dataSource, String key, {dynamic defaultValue = ''}) {
    if (dataSource == null || !(dataSource is Map)) {
      return defaultValue;
    }
    dynamic data = dataSource[key];
    if (data is num) {
      return Decimal.parse(data.toString()).toString();
    }
    return data == null ? defaultValue : data;
  }

  /// 格式化图片地址
  static String initImageUrl(String imageUrl) {
    if (imageUrl == null || imageUrl.length == 0) return null;
    if (imageUrl.contains('http') || imageUrl.contains('https')) {
      return imageUrl;
    }
    String ftpService = BaseStorageUtil.storageFtpService;
    return ftpService + imageUrl;
  }

  static String transformString(dynamic data) {
    return data == null ? '' : data.toString();
  }

  /// 过滤路径
  static Future<List<T>> filterAssetEntity<T>({@required List<AssetEntity> assetEntityList, @required Function(File, int) fn}) async {
    List<T> _list = [];
    for (int i = 0; i < assetEntityList.length; i++) {
      File file = await assetEntityList[i].file;
      _list.add(fn(file, i));
    }
    return _list;
  }

  /// 处理请求的地址 -- 拼接上微服务名称
  static String handlerServicePath(String service) {
    if (service.startsWith('local'))
      return service.replaceFirst('local', '');
    else if (service.startsWith('x3') || service.startsWith('/bi/datasets'))
      return service;
    else if (service.startsWith('/bills'))
      return '/${ServiceConfig.billsCenter}$service';
    else if (service.startsWith('/archive') || service.startsWith('/userpower'))
      return '/${ServiceConfig.archiveCenter}$service';
    else if (service.startsWith('/vipbills'))
      return '/${ServiceConfig.vipBillsCenter}$service';
    else if (service.startsWith('/bi'))
      return '/${ServiceConfig.reportCenter}$service';
    else if (service.startsWith('/vip'))
      return '/${ServiceConfig.vipCenter}$service';
    else if (service.startsWith('/retail'))
      return '/${ServiceConfig.retailCenter}$service';
    else if (service.startsWith('/system/tools')) return '/${ServiceConfig.flowCenter}$service';
    return service;
  }

  /// 获取Hero Tag
  static String getHeroTag(String text) {
    return new Random().nextInt(1000).toString() + DateTime.now().millisecondsSinceEpoch.toString();
  }

  /// 计算文本Size，需要主要maxWidth字段，该字段决定了文本最大宽度，默认为double.infinity
  static Size boundingTextSize(BuildContext context, String text, TextStyle style, {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text == null || text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr, locale: Localizations.localeOf(context), text: TextSpan(text: text, style: style), maxLines: maxLines)..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  /// 判断当前图片地址是否是svg图片地址
  /// 判断条件是以".svg"/".SVG"结尾
  static bool isTheSVGPicture(String url) {
    if (url == null || url.isEmpty) return false;
    if (!url.contains(".")) return false;
    List<String> list = url.split('.');
    if (list == null || list.length == 0) return false;
    if (list.last == 'svg' || list.last == 'SVG') return true;
    return false;
  }

  /// 当前文件是否为视频类型
  static bool isVideoFile(String link) {
    if (link == null || link.isEmpty) return false;
    if (link.contains(".MP4")) return true;
    if (link.contains(".mp4")) return true;
    if (link.contains(".MOV")) return true;
    if (link.contains(".mov")) return true;
    return false;
  }
}
